################################
###                          ###
### Women and Party Building ###
###                          ###
###     code_appendix.R      ###
###                          ###
################################

# This script performs the analyses for the appendix / supplementary materials.

rm( list=ls() )
library(rdrobust)
library(plotrix)
library(rdd)
library(stargazer)
library(lfe)

cat("Beginning appendix analyses...\n")

# This line uses the rstudioapi package to set the working directory to the same folder where this script is saved.
# Alternatively, you can use setwd( PATH ) to set this directory manually
try(setwd(dirname(rstudioapi::getActiveDocumentContext()$path)))

# Loads helper functions
source("code_helperfunctions.R")

# Creates sub-folders for saving the results
dir.create("../3_output", showWarnings = FALSE)
dir.create("../3_output/figures", showWarnings = FALSE)
dir.create("../3_output/tables", showWarnings = FALSE)
dir.create("../3_output/appendix", showWarnings = FALSE)


### TABLE A.1. Summary Statistics

women <- readRDS("../1_data/analysis/data_analysis_RDD_women.rds")
men <- readRDS("../1_data/analysis/data_analysis_RDD_women.rds")

vars <- c( "Recruit.Share", "Gender.Gap", "Attrition.Rate", "Attrition.Rate.Female", "Attrition.Rate.Male",  "Renominated", "Advanced", "Cumulative.Female.Recruits.Share")
stargazer(women[, vars], omit.summary.stat = c("p25", "p75"), covariate.labels = c( "Recruitment Rate", "Gender Gap in Recruitment", "Attrition Rate (All Members)", "Attrition Rate (Female Members)", "Attrition Rate (Male Members)", "Renominated", "Advanced", "Women's Recruitment in Previous Terms"),
          title="Summary Statistics", out="../3_output/appendix/tableA1.tex")




### FIGURE D.1. Placebo RD Tests on Pre-Treatment Variables

women <- readRDS("../1_data/analysis/data_analysis_RDD_women.rds")

# Use rdrobust() to calculate p-values for placebo RD tests on variables defined prior to treatment
balance.vars <- c("Recruit.Share.Lagged", "Gender.Gap.Lagged", "Attrition.Rate.Lagged", "University", "Incumbent", "Married", "Age", "Dynastic", "Insider", "Time.In.Party", "First.Female.Mayor", "Prior.Female.Mayors", "Challenger_Incumbent", "Challenger_Time.In.Politics", "Illiteracy_2000", "UrbanizationRate_2000", "HDI_2000", "Population_2000", "Female.Participation.Rate", "Voter.Gender.Ratio", "PT.Deputies.Voteshare")
vars.labels <- c("Total Recruitment", "Gender Gap", "Attrition Rate", "University Education", "Incumbent", "Married", "Age", "Dynastic Candidate", "Party Insider", "Time in Politics", "First Female Mayor", "# Prior Female Mayors", "Incumbent Rival", "Rival's Time in Politics", "Illiteracy Rate", "Urbanization Rate", "Human Development Index", "Population", "Female Labor Force Participation", "Gender Balance of Electorate", "PT Voteshare")
p.values <- c()
results <- c()
for(var in balance.vars){
  mod <- rdrobust(women[, var], women[, "Margin"])
  results <- rbind(results, results.formater(mod))
  p.values <- c(p.values, mod$pv[3])
}

# Create figure
pdf("../3_output/appendix/figureD1.pdf", width=6, height=5)
par(mar=c(4, 12, 3, 3), las=1)
places <- 24-c(1:3, 5:15, 17:23)
plot(p.values, places, xlim=c(0, 1), ylim=c(.5, 24.5), pch=16, ylab="", xlab="P-value", yaxt="n", xaxs="i", yaxs="i")
abline(v=0.05, col="red")
abline(v=0.1, col="blue")
axis(2, at=places, labels=vars.labels, cex.axis=.7)
axis(2, at=c(24, 20, 8), labels=c("Lagged DVs                                 ", "Candidate Variables                     ", "Municipal Variables                     "), cex.axis=.8, tick = F, hadj=1)
segments(-1, places, 2, places, lty=3, lwd=.5)
dev.off()

# Create corresponding table for the appendix
table <-results[, !(names(results) == "Model")]
rownames(table) <-vars.labels
stargazer(table, summary=F, out="../3_output/appendix/tableD1.tex",
          title="Placebo RD Tests in Table Format", label="tab:placebo", font.size = "small")




### FIGURE E.1. Density Plot of the Running Variable (Margin of Victory)

women <- readRDS("../1_data/analysis/data_analysis_RDD_women.rds")

pdf("../3_output/appendix/figureE1.pdf", width=5, height=3.5)
par(las=1, mar=c(5, 5, 1, 1))
rdd::DCdensity(women$Margin)
title(xlab="Female Candidate's Margin of Victory\n(Running Variable)", ylab="Density")
dev.off()



### FIGURE F.1. RD Estimates For Alternative Bandwidths

women <- readRDS("../1_data/analysis/data_analysis_RDD_women.rds")

pdf("../3_output/appendix/figureF1.pdf", width=6, height=6)
par(las=1, mfrow=c(2,1), mar=c(4,3,3,3))
thresholds <- seq(.01, .3, by=.01)

# These loops iterate through alternative RDD bandwidths (h) from 0.01 to 0.3 in order to discern
# whether the main RDD results are robust to bandwidths other than the CTT optimal bandwidth
results <- c()
for(h in thresholds){
  mod <- rdrobust(women$Gender.Gap, women$Margin, h=h)
  results <- rbind(results, c(mod$coef[3], mod$ci[3,]))
}
plotCI(x=thresholds, y=results[,1], ui=results[,3], li=results[,2], pch=16, ylab="", xlab="Bandwidths", main="Gender Imbalance in Recruitment")
abline(h=0)

thresholds <- seq(.01, .3, by=.01)
results <- c()
for(h in thresholds){
  mod <- rdrobust(women$Recruit.Share, women$Margin, h=h)
  results <- rbind(results, c(mod$coef[3], mod$ci[3,]))
}
plotCI(x=thresholds, y=results[,1], ui=results[,3], li=results[,2], pch=16, ylab="", xlab="Bandwidths", main="Total Recruitment")
abline(h=0)
dev.off()



### FIGURE G.1. RD Estimates At Different Placebo Thresholds

women <- readRDS("../1_data/analysis/data_analysis_RDD_women.rds")

pdf("../3_output/appendix/figureG1.pdf", width=6, height=6)
par(las=1, mfrow=c(2,1), mar=c(4,3,3,3))
cuts <- seq(-.4, .4, by=.05)
results <- c()

# These loops iterate through placebo (non-zero) cut-points and recalculate the main model using those cuts
for(cut in cuts){
  mod <- rdrobust(women$Gender.Gap, women$Margin, c = cut)
  results <- rbind(results, c(mod$coef[3], mod$ci[3,]))
}
plotCI(x=cuts, y=results[,1], ui=results[,3], li=results[,2], pch=16, ylab="", xlab="Treatment Thresholds", main="Gender Gap in Recruitment")
abline(h=0)

cuts <- seq(-.4, .4, by=.05)
results <- c()
for(cut in cuts){
  mod <- rdrobust(women$Recruit.Share, women$Margin, c = cut)
  results <- rbind(results, c(mod$coef[3], mod$ci[3,]))
}
plotCI(x=cuts, y=results[,1], ui=results[,3], li=results[,2], pch=16, ylab="", xlab="Treatment Thresholds", main="Total Recruitment")
abline(h=0)
dev.off()




### FIGURE H.1. RD Estimates for Higher-Order Polynomial Specifications

women <- readRDS("../1_data/analysis/data_analysis_RDD_women.rds")
men <- readRDS("../1_data/analysis/data_analysis_RDD_men.rds")

# Re-calculate the main RDD models using different orders of  local-polynomials to construct the point-estimator
women.1 <- rdrobust(women$Gender.Gap, women$Margin, p=1)
men.1 <- rdrobust(men$Gender.Gap, men$Margin, p=1)
women.2 <- rdrobust(women$Gender.Gap, women$Margin, p=2)
men.2 <- rdrobust(men$Gender.Gap, men$Margin, p=2)
women.3 <- rdrobust(women$Gender.Gap, women$Margin, p=3)
men.3 <- rdrobust(men$Gender.Gap, men$Margin, p=3)
women.4 <- rdrobust(women$Gender.Gap, women$Margin, p=4)
men.4 <- rdrobust(men$Gender.Gap, men$Margin, p=4)

coefs <- c(women.1$coef[3], men.1$coef[3], women.2$coef[3], men.2$coef[3], women.3$coef[3], men.3$coef[3], women.4$coef[3], men.4$coef[3])
confs <- rbind(women.1$ci[3,], men.1$ci[3,], women.2$ci[3,], men.2$ci[3,], women.3$ci[3,], men.3$ci[3,], women.4$ci[3,], men.4$ci[3,])

pdf("../3_output/appendix/figureH1.pdf", width=5, height=3.5)
par(las=1, mar=c(5,5,1,1))
gap <- .1
places <- sort(c(1:4  + gap, 1:4  - gap))
plotCI(places, coefs, ui=confs[,2], li=confs[,1], pch=16, col=c("red", "blue"), xaxt="n", ylab="Effect on Gender Gap", xlab="Order of Polynomial", xlim=c(.5, 4.5), ylim=c(-2.5, 2.5))
abline(h=0, lty=3)
axis(1, 1:4, c("1st", "2nd", "3rd", "4th"))
legend("topright", pch=16, col=c("red", "blue"), c("Female Candidates", "Male Candidates"))
dev.off()

higherorderpolynomials <- rbind(results.formater(women.1,  "Female Candidates, Linear"),
                                results.formater(men.1,  "Male Candidates, Linear"),
                                results.formater(women.2,  "Female Candidates, Quadratic"),
                                results.formater(men.2,  "Male Candidates, Quadratic"),
                                results.formater(women.3,  "Female Candidates, Cubic"),
                                results.formater(men.3,  "Male Candidates, Cubic"),
                                results.formater(women.4,  "Female Candidates, Quartic"),
                                results.formater(men.4,  "Male Candidates, Quartic"))
stargazer(as.matrix(higherorderpolynomials), covariate.labels = c("Model", "Estimate", "95\\% CI", "p", "h", "n"), 
          title="RD Estimates for Higher-Order Polynomial Specifications (Corresponds to Appendix Figure H1)", 
          out="../3_output/appendix/tableS1.tex")




### TABLE I.1 and TABLE I.2: Characteristics of Female and Male Mayors

# Combines the datasets for female and male candidates
# (Note: For reasons discussed in the Appendix section "Details on the Regression Discontinuity Comparisons," 
# we do not analyze the data this way in the article's main analyses. The purpose of this Appendix analysis is solely
# to assess the extent to which candidate gender is correlated with other theoretically-relevant candidate characteristics 
# that are not automatically accounted for by the RD design.)
women <- readRDS("../1_data/analysis/data_analysis_RDD_women.rds")
men <- readRDS("../1_data/analysis/data_analysis_RDD_men.rds")
men$Margin <- -men$Margin # Under this new setup, a positive margin of victory means that the woman won, while a negative margin means that the man won
women.matched <- women[paste(women$Year, women$MunCode) %in% paste(men$Year, men$MunCode),]
men.matched <- men[paste(men$Year, men$MunCode) %in% paste(women$Year, women$MunCode),]
women.matched <- women
men.matched <- men
women.matched$Female.Mayor <- TRUE
men.matched$Female.Mayor <- FALSE
data <- rbind(women.matched[women.matched$Winner,], men.matched[men.matched$Winner,])

# Create binary variables for whether the candidate belongs to major parties
data$PT <- as.numeric(data$Party == "PT")
data$PSDB <- as.numeric(data$Party == "PSDB")
data$MDB <- as.numeric(data$Party == "MDB")
data$DEM <- as.numeric(data$Party == "DEM")
data$PP <- as.numeric(data$Party == "PP")
data$PL <- as.numeric(data$Party == "PL")

# This loop iterates through different pre-treatment candidate characteristics
vars <- c("Incumbent", "University", "Married", "Dynastic", "Age", "Time.In.Party", "Time.In.Politics", "PT", "PSDB", "MDB", "DEM", "PP", "PL")
results.full <- c()
results.close <- c()
for(v in vars){
  y <- data[, v]
  
  # Performs simple t-test for full sample
  mod1 <- t.test(y ~ data$Female.Mayor)
  
  # Performs placebo RD estimation
  modrd <- rdrobust(y, data$Margin)
  
  # Performs t-test for observations within bandwidth of h = 0.05 
  y <- data[abs(data$Margin) < .05, v]
  mod2 <- t.test(y ~ data$Female.Mayor[abs(data$Margin) < .05])
  
  results.full <- rbind(results.full, data.frame(Men=round(mod1$estimate[1], 3), Women=round(mod1$estimate[2], 3), pvalue=round(mod1$p.value, 3)))
  results.close <- rbind(results.close, data.frame(Men=round(mod2$estimate[1], 3), Women=round(mod2$estimate[2], 3), pvalue=round(mod2$p.value, 3), rd.pvalue=round(modrd$pv[3], 3)))
}

rownames(results.full) <- vars
rownames(results.close) <- vars

# Formats Results into Table
rownames(results.full) <- c("Incumbent", "University Education", "Married", "Dynastic Candidate", "Age", "Years in Party", "Years in Politics", "PT", "PSDB", "MDB", "DEM", "PP", "PL")
rownames(results.close) <- c("Incumbent", "University Education", "Married", "Dynastic Candidate", "Age", "Years in Party", "Years in Politics", "PT", "PSDB", "MDB", "DEM", "PP", "PL")
stargazer(results.full, summary=F, covariate.labels = c("", "Male Mayors", "Female Mayors", "DM p-value"), 
          column.labels=c("Incumbent", "University Education", "Married", "Dynastic Candidate", "Age", "Years in Party", "Years in Politics", "PT", "PSDB", "MDB", "DEM", "PP", "PL"),
          title="Full Sample", label="tab:Candidate_Balance_Full",
          out="../3_output/appendix/tableI1.tex")
stargazer(results.close, summary=F, covariate.labels = c("", "Male Mayors", "Female Mayors", "DM p-value", "RD p-value"),
          title="Close Races", label="tab:Candidate_Balance_Competitive",
          out="../3_output/appendix/tableI2.tex")






### FIGURE J.1. Two-Way Fixed Effects Regression Estimates of the Effect of Female and Male Mayors

data <- readRDS("../1_data/analysis/data_analysis_MunicipalitiesPanel.rds")

mod.gap <- felm(Gender.Gap ~ Treated.Women + Treated.Men | MunCode + Year  | 0 | MunCode, data=data)
mod.recruit <- felm(Recruit.Share ~ Treated.Women + Treated.Men | MunCode + Year  | 0 | MunCode, data=data)
mod.recruitwomen <- felm(Female.Recruit.Share ~ Treated.Women + Treated.Men | MunCode + Year  | 0 | MunCode, data=data)
mod.recruitmen <- felm(Male.Recruit.Share ~ Treated.Women + Treated.Men | MunCode + Year  | 0 | MunCode, data=data)

results.gap <-  rbind(cbind(mod.gap$coefficients, confint(mod.gap)), difference.coefficients(mod.gap))
results.recruit <-  rbind(cbind(mod.recruit$coefficients, confint(mod.recruit)), difference.coefficients(mod.recruit))
results.recruitwomen <-  rbind(cbind(mod.recruitwomen$coefficients, confint(mod.recruitwomen)), difference.coefficients(mod.recruitwomen))
results.recruitmen <-  rbind(cbind(mod.recruitmen$coefficients, confint(mod.recruitmen)), difference.coefficients(mod.recruitmen))


pdf("../3_output/appendix/figureJ1.pdf", width=6, height=5)
par(mfrow=c(2,2), las=1, mar=c(2.5,3,2, 1))
places <- 1:3
cex.main = .9
plotCI(places, results.gap[, 1], li=results.gap[, 2], ui=results.gap[, 3], pch=16, xlim=c(.7, 3.3), xaxt="n", xlab="", ylab="", main="(A) Gender Gap", cex.main = cex.main)
axis(1, places, c("Female\nMayors", "Male\nMayors", "Difference\n"), tick=F)
abline(h=0, lty=3)
plotCI(places, results.recruit[, 1], li=results.recruit[, 2], ui=results.recruit[, 3], pch=16, xlim=c(.7, 3.3), xaxt="n", xlab="", ylab="", main="(B) Membership Recruitment", ylim=c(-1, 4), cex.main = cex.main)
axis(1, places, c("Female\nMayors", "Male\nMayors", "Difference\n"), tick=F)
abline(h=0, lty=3)
points(places, results.recruit[, 1], pch=21, bg=ifelse(results.recruit[,2] * results.recruit[,3] > 0, "black", "white"))
plotCI(places, results.recruitwomen[, 1], li=results.recruitwomen[, 2], ui=results.recruitwomen[, 3],  pch=16, xlim=c(.7, 3.3), xaxt="n", xlab="", ylab="", main="(C) Recruitment of Women", ylim=c(-1, 4), cex.main = cex.main)
axis(1, places, c("Female\nMayors", "Male\nMayors", "Difference\n"), tick=F)
abline(h=0, lty=3)
plotCI(places, results.recruitmen[, 1], li=results.recruitmen[, 2], ui=results.recruitmen[, 3], pch=16, xlim=c(.7, 3.3), xaxt="n", xlab="", ylab="", main="(D) Recruitment of Men", ylim=c(-1, 4), cex.main = cex.main)
axis(1, places, c("Female\nMayors", "Male\nMayors", "Difference\n"), tick=F)
abline(h=0, lty=3)
points(places, results.recruitmen[, 1], pch=21, bg=ifelse(results.recruitmen[,2] * results.recruitmen[,3] > 0, "black", "white"))
dev.off()

stargazer(mod.gap, mod.recruit, mod.recruitwomen, mod.recruitmen,
          add.lines = list(c("Municipality Fixed Effects", "Yes", "Yes", "Yes", "Yes"),
                           c("Term Fixed Effects", "Yes", "Yes", "Yes", "Yes")),
          dep.var.labels = c("Gender", "Membership", "Recruitment", "Recruitment"),
           column.labels = c("Gap", "Recruitment", "of Women", "of Men"),
          covariate.labels = c("Female Mayor", "Male Mayor"),
          omit.stat=c("f", "ser", "adj.rsq"),
          font.size = "small",
          title="Effect of Female and Male Mayors on Membership Recruitment", 
          out="../3_output/appendix/tableJ1.tex")






### FIGURES K.1, K.2, and K.3: Heterogeneous Effects

# Reloads RDD data
women <- readRDS("../1_data/analysis/data_analysis_RDD_women.rds")

# FIGURE K.1: Candidate Type
dynastic.yes <- rdrobust(y=women$Gender.Gap[women$Dynastic], x=women$Margin[women$Dynastic])
dynastic.no <- rdrobust(y=women$Gender.Gap[!women$Dynastic], x=women$Margin[!women$Dynastic])
incumbent.yes <- rdrobust(y=women$Gender.Gap[women$Incumbent], x=women$Margin[women$Incumbent])
incumbent.no <- rdrobust(y=women$Gender.Gap[!women$Incumbent], x=women$Margin[!women$Incumbent])
prioroffice.yes <- rdrobust(y=women$Gender.Gap[women$Prior.Office %in% c("VEREADOR", "VICE-PREFEITO")], x=women$Margin[women$Prior.Office %in% c("VEREADOR", "VICE-PREFEITO")])
prioroffice.no <- rdrobust(y=women$Gender.Gap[women$Prior.Office == "None"], x=women$Margin[women$Prior.Office == "None"])
insider.yes <- rdrobust(y=women$Gender.Gap[women$Time.In.Party > 4], x=women$Margin[women$Time.In.Party > 4])
insider.no <- rdrobust(y=women$Gender.Gap[women$Time.In.Party <= 4], x=women$Margin[women$Time.In.Party <= 4])

# Note: difference.calculator() is a helper function that can be found in helperfunctions.R
dynastic <- difference.calculator(dynastic.yes, dynastic.no)
incumbent <- difference.calculator(incumbent.yes, incumbent.no)
prioroffice <- difference.calculator(prioroffice.yes, prioroffice.no)
insider <- difference.calculator(insider.yes, insider.no)

pdf("../3_output/appendix/figureK1.pdf", width=6, height=4)
which <- 1:2
par(mfrow=c(2,2), las=1, mar=c(2,4,2,2))
plotCI(which, dynastic[which, 1], ui=dynastic[which, 3], li=dynastic[which, 2], pch=16, lwd=2, cex=1, xlim=c(.5, 2.5), ylim=c(-3, 1), xaxt="n", xlab="", ylab="Effect on Gender Gap", main="(A) Dynastic Candidate", cex.main=.9)
abline(h=0, lty=3)
axis(1, 1:2, labels = c("Yes\n", "No\n"), tick = F)
plotCI(which, incumbent[which, 1], ui=incumbent[which, 3], li=incumbent[which, 2], pch=16, lwd=2, cex=1, xlim=c(.5, 2.5), ylim=c(-3, 1), xaxt="n", xlab="", ylab="Effect on Gender Gap", main="(B) Incumbent", cex.main=.9)
abline(h=0, lty=3)
axis(1, 1:2, labels = c("Yes\n", "No\n"), tick = F)
plotCI(which, prioroffice[which, 1], ui=prioroffice[which, 3], li=prioroffice[which, 2], pch=16, lwd=2, cex=1, xlim=c(.5, 2.5), ylim=c(-5, 1), xaxt="n", xlab="", ylab="Effect on Gender Gap", main="(C) Held Prior Office", cex.main=.9)
abline(h=0, lty=3)
axis(1, 1:2, labels = c("Yes\n", "No\n"), tick = F)
plotCI(which, insider[which, 1], ui=insider[which, 3], li=insider[which, 2], pch=16, lwd=2, cex=1, xlim=c(.5, 2.5), ylim=c(-3, 1), xaxt="n", xlab="", ylab="Effect on Gender Gap", main="(D) Party Insider", cex.main=.9)
abline(h=0, lty=3)
axis(1, 1:2, labels = c("Yes\n", "No\n"), tick = F)
dev.off()

candidate.type <- rbind(results.formater(dynastic.yes,  "Dynastic Candidate"),
                      results.formater(dynastic.no, "Not Dynastic Candidate"),
                      results.formater(incumbent.yes,  "Incumbent"),
                      results.formater(incumbent.no,  "Not Incumbent"),
                      results.formater(prioroffice.yes,  "Held Prior Office"),
                      results.formater(prioroffice.no,  "Not Prior Office"),
                      results.formater(insider.yes,  "Party Insider"),
                      results.formater(insider.no,  "Not Party Insider"))
stargazer(as.matrix(candidate.type), covariate.labels = c("Model", "Estimate", "95\\% CI", "p", "h", "n"), 
          title="Effects by Candidate Type",
          out="../3_output/appendix/tableS2.tex")




# FIGURE K.2: Municipality Type

women <- readRDS("../1_data/analysis/data_analysis_RDD_women.rds")

median.development <- median(women$HDI_2010, na.rm=T)
development.high <- rdrobust(y=women$Gender.Gap[women$HDI_2010 > median.development], x=women$Margin[women$HDI_2010 > median.development])
development.low <- rdrobust(y=women$Gender.Gap[women$HDI_2010 < median.development], x=women$Margin[women$HDI_2010 < median.development])
median.laborparticipation <- median(women$Female.Participation.Rate, na.rm=T)
laborparticipation.high <- rdrobust(y=women$Gender.Gap[women$Female.Participation.Rate > median.laborparticipation], x=women$Margin[women$Female.Participation.Rate > median.laborparticipation])
laborparticipation.low <- rdrobust(y=women$Gender.Gap[women$Female.Participation.Rate < median.laborparticipation], x=women$Margin[women$Female.Participation.Rate < median.laborparticipation])
women$Electorate <- women$Female.Voters + women$Male.Voters
median.population <- median(women$Electorate, na.rm=T)
population.high <- rdrobust(y=women$Gender.Gap[women$Electorate > median.population], x=women$Margin[women$Electorate > median.population])
population.low <- rdrobust(y=women$Gender.Gap[women$Electorate < median.population], x=women$Margin[women$Electorate < median.population])


development <- difference.calculator(development.high, development.low)
laborforce <- difference.calculator(laborparticipation.high, laborparticipation.low)
population <- difference.calculator(population.high, population.low)


pdf("../3_output/appendix/figureK2.pdf", width=6, height=4)
which <- 1:2
par(mfrow=c(2,2), las=1, mar=c(2,4,2,2))
plotCI(which, development[which, 1], ui=development[which, 3], li=development[which, 2], pch=16, lwd=2, cex=1, xlim=c(.5, 2.5), ylim=c(-3, 1), xaxt="n", xlab="", ylab="Effect on Gender Gap", main="(A) Human Development", cex.main=.9)
abline(h=0, lty=3)
axis(1, 1:2, labels = c("High\n", "Low\n"), tick = F)
plotCI(which, laborforce[which, 1], ui=laborforce[which, 3], li=laborforce[which, 2], pch=16, lwd=2, cex=1, xlim=c(.5, 2.5), ylim=c(-3, 1), xaxt="n", xlab="", ylab="Effect on Gender Gap", main="(B) Female Labor Force Participation", cex.main=.9)
abline(h=0, lty=3)
axis(1, 1:2, labels = c("High\n", "Low\n"), tick = F)
plotCI(which, population[which, 1], ui=population[which, 3], li=population[which, 2], pch=16, lwd=2, cex=1, xlim=c(.5, 2.5), ylim=c(-3, 1), xaxt="n", xlab="", ylab="Effect on Gender Gap", main="(C) Size of Municipal Electorate", cex.main=.9)
abline(h=0, lty=3)
axis(1, 1:2, labels = c("High\n", "Low\n"), tick = F)
dev.off()

municipality.type <- rbind(results.formater(development.high,  "High Development"),
                        results.formater(development.low, "Low Development"),
                        results.formater(laborparticipation.high,  "High Female Labor Force Participation"),
                        results.formater(laborparticipation.low,  "Low Female Labor Force Participation"),
                        results.formater(population.high,  "Large Electorate"),
                        results.formater(population.low,  "Low Electorate"))
stargazer(as.matrix(municipality.type), covariate.labels = c("Model", "Estimate", "95\\% CI", "p", "h", "n"), 
          title="Effects by Municipality Type",
          out="../3_output/appendix/tableS3.tex")



# FIGURE K.3: Party Type

women <- readRDS("../1_data/analysis/data_analysis_RDD_women.rds")
men <- readRDS("../1_data/analysis/data_analysis_RDD_women.rds")
party.data <- readRDS("../1_data/raw/data_raw_PartyData.rds")

women <- merge(women, party.data, by=c("Party"), all.x=T)
men <- merge(men, party.data, by=c("Party"), all.x=T)
women$PartyCentralized <- women$DALP_Centralization > median(party.data$DALP_Centralization, na.rm=T)
men$PartyCentralized <- women$DALP_Centralization > median(party.data$DALP_Centralization, na.rm=T)

left.yes <- rdrobust(y=women$Gender.Gap[women$PartyIdeologyLeft], x=women$Margin[women$PartyIdeologyLeft])
left.no <- rdrobust(y=women$Gender.Gap[!women$PartyIdeologyLeft], x=women$Margin[!women$PartyIdeologyLeft])
policyseeking.yes <- rdrobust(y=women$Gender.Gap[women$PartyPolicySeeking], x=women$Margin[women$PartyPolicySeeking])
policyseeking.no <- rdrobust(y=women$Gender.Gap[!women$PartyPolicySeeking], x=women$Margin[!women$PartyPolicySeeking])
centralized.yes <- rdrobust(y=women$Gender.Gap[women$PartyCentralized], x=women$Margin[women$PartyCentralized])
centralized.no <- rdrobust(y=women$Gender.Gap[!women$PartyCentralized], x=women$Margin[!women$PartyCentralized])
womanleadership.yes <- rdrobust(y=women$Gender.Gap[women$PartyHighWomanLeadership], x=women$Margin[women$PartyHighWomanLeadership])
womanleadership.no <- rdrobust(y=women$Gender.Gap[!women$PartyHighWomanLeadership], x=women$Margin[!women$PartyHighWomanLeadership])

left <- difference.calculator(left.yes, left.no)
policyseeking <- difference.calculator(policyseeking.yes, policyseeking.no)
centralized <- difference.calculator(centralized.yes, centralized.no)
womanleadership <- difference.calculator(womanleadership.yes, womanleadership.no)

pdf("../3_output/appendix/figureK3.pdf", width=6, height=4)
which <- 1:2
par(mfrow=c(2,2), las=1, mar=c(2,4,2,2))
plotCI(which, left[which, 1], ui=left[which, 3], li=left[which, 2], pch=16, lwd=2, cex=1, xlim=c(.5, 2.5), ylim=c(-3, 1), xaxt="n", xlab="", ylab="Effect on Gender Gap", main="(A) Party Ideology", cex.main=.9)
abline(h=0, lty=3)
axis(1, 1:2, labels = c("Leftist\n", "Not Leftist\n"), tick = F)
plotCI(which, policyseeking[which, 1], ui=policyseeking[which, 3], li=policyseeking[which, 2], pch=16, lwd=2, cex=1, xlim=c(.5, 2.5), ylim=c(-3, 1), xaxt="n", xlab="", ylab="Effect on Gender Gap", main="(B) Policy-Seeking Party", cex.main=.9)
abline(h=0, lty=3)
axis(1, 1:2, labels = c("Yes\n", "No\n"), tick = F)
plotCI(which, centralized[which, 1], ui=centralized[which, 3], li=centralized[which, 2], pch=16, lwd=2, cex=1, xlim=c(.5, 2.5), ylim=c(-3, 1), xaxt="n", xlab="", ylab="Effect on Gender Gap", main="(C) Party Structure", cex.main=.9)
abline(h=0, lty=3)
axis(1, 1:2, labels = c("Centralized\n", "Decentralized\n"), tick = F)
plotCI(which, womanleadership[which, 1], ui=womanleadership[which, 3], li=womanleadership[which, 2], pch=16, lwd=2, cex=1, xlim=c(.5, 2.5), ylim=c(-3, 1), xaxt="n", xlab="", ylab="Effect on Gender Gap", main="(D) Women in Party Leadership", cex.main=.9)
abline(h=0, lty=3)
axis(1, 1:2, labels = c("High (>20%)\n", "Low (<20%)\n"), tick = F)
dev.off()

candidate.type <- rbind(results.formater(left.yes,  "Leftist Party"),
                        results.formater(left.no, "Centrist or Right-wing Party"),
                        results.formater(policyseeking.yes,  "Policy-Seeking Party"),
                        results.formater(policyseeking.no,  "Not Policy-Seeking Party"),
                        results.formater(centralized.yes,  "Centralized Party"),
                        results.formater(centralized.no,  "Decentralized Party"),
                        results.formater(womanleadership.yes,  "High Women in Party Leadership"),
                        results.formater(womanleadership.no,  "Low Women in Party Leadership"))
stargazer(as.matrix(candidate.type), covariate.labels = c("Model", "Estimate", "95\\% CI", "p", "h", "n"), 
          title="Effects by Party Type",
          out="../3_output/appendix/tableS4.tex")




### FIGURE L.1. The Effect of Incumbency on Party-Switching, by Party of Origin

women <- readRDS("../1_data/analysis/data_analysis_RDD_women.rds")
men <- readRDS("../1_data/analysis/data_analysis_RDD_men.rds")

mod.switching.women.female.pt <- rdrobust(y=women$Switch.Rate.Female[women$Party == "PT"], x=women$Margin[women$Party == "PT"])
mod.switching.women.male.pt <- rdrobust(y=men$Switch.Rate.Female[men$Party == "PT"], x=men$Margin[men$Party == "PT"])
mod.switching.men.female.pt <- rdrobust(y=women$Switch.Rate.Male[women$Party == "PT"], x=women$Margin[women$Party == "PT"])
mod.switching.men.male.pt <- rdrobust(y=men$Switch.Rate.Male[men$Party == "PT"], x=men$Margin[men$Party == "PT"])

mod.switching.women.female.psdb <- rdrobust(y=women$Switch.Rate.Female[women$Party == "PSDB"], x=women$Margin[women$Party == "PSDB"])
mod.switching.women.male.psdb <- rdrobust(y=men$Switch.Rate.Female[men$Party == "PSDB"], x=men$Margin[men$Party == "PSDB"])
mod.switching.men.female.psdb <- rdrobust(y=women$Switch.Rate.Male[women$Party == "PSDB"], x=women$Margin[women$Party == "PSDB"])
mod.switching.men.male.psdb <- rdrobust(y=men$Switch.Rate.Male[men$Party == "PSDB"], x=men$Margin[men$Party == "PSDB"])

mod.switching.women.female.mdb <- rdrobust(y=women$Switch.Rate.Female[women$Party == "MDB"], x=women$Margin[women$Party == "MDB"])
mod.switching.women.male.mdb <- rdrobust(y=men$Switch.Rate.Female[men$Party == "MDB"], x=men$Margin[men$Party == "MDB"])
mod.switching.men.female.mdb <- rdrobust(y=women$Switch.Rate.Male[women$Party == "MDB"], x=women$Margin[women$Party == "MDB"])
mod.switching.men.male.mdb <- rdrobust(y=men$Switch.Rate.Male[men$Party == "MDB"], x=men$Margin[men$Party == "MDB"])

mod.switching.women.female.dem <- rdrobust(y=women$Switch.Rate.Female[women$Party == "DEM"], x=women$Margin[women$Party == "DEM"])
mod.switching.women.male.dem <- rdrobust(y=men$Switch.Rate.Female[men$Party == "DEM"], x=men$Margin[men$Party == "DEM"])
mod.switching.men.female.dem <- rdrobust(y=women$Switch.Rate.Male[women$Party == "DEM"], x=women$Margin[women$Party == "DEM"])
mod.switching.men.male.dem <- rdrobust(y=men$Switch.Rate.Male[men$Party == "DEM"], x=men$Margin[men$Party == "DEM"])

pdf("../3_output/appendix/figureL1.pdf", width=8, height=4)

# Women members
coefs <- c(mod.switching.women.female.pt$coef[3], mod.switching.women.male.pt$coef[3], mod.switching.women.female.psdb$coef[3], mod.switching.women.male.psdb$coef[3], mod.switching.women.female.mdb$coef[3], mod.switching.women.male.mdb$coef[3], mod.switching.women.female.dem$coef[3], mod.switching.women.male.dem$coef[3])
confs <- rbind(mod.switching.women.female.pt$ci[3,], 
               mod.switching.women.male.pt$ci[3,], 
               mod.switching.women.female.psdb$ci[3,], 
               mod.switching.women.male.psdb$ci[3,], 
               mod.switching.women.female.mdb$ci[3,], 
               mod.switching.women.male.mdb$ci[3,], 
               mod.switching.women.female.dem$ci[3,],
               mod.switching.women.male.dem$ci[3,])

gap <- .1
places <- c(1-gap, 1+gap, 2-gap, 2+gap, 3-gap, 3+gap, 4-gap, 4+gap)
par(las=1, mfrow=c(1, 2), mar=c(2, 4, 2, 1))
suppressWarnings(plotCI(places, coefs, ui=confs[,2], li=confs[,1], pch=c(16, 15), lwd=2, cex=1, xlim=c(.5, 4.5), ylim=c(-.4, .4), xaxt="n", xlab="", ylab="Effect on Party Switching", main="Female Party Members", cex.main=.9, col=c("red", "blue")))
abline(h=0, lty=3)
legend("topright", lwd=2, pch=c(16,15), col=c("red", "blue"), c("Female Mayor", "Male Mayor"), bty="n")
axis(1, 1:4, labels = c("PT\n", "PSDB\n", "MDB\n", "DEM\n"), tick = F)

# Men members
coefs <- c(mod.switching.men.female.pt$coef[3], mod.switching.men.male.pt$coef[3], mod.switching.men.female.psdb$coef[3], mod.switching.men.male.psdb$coef[3], mod.switching.men.female.mdb$coef[3], mod.switching.men.male.mdb$coef[3], mod.switching.men.female.dem$coef[3], mod.switching.men.male.dem$coef[3])
confs <- rbind(mod.switching.men.female.pt$ci[3,], 
               mod.switching.men.male.pt$ci[3,], 
               mod.switching.men.female.psdb$ci[3,], 
               mod.switching.men.male.psdb$ci[3,], 
               mod.switching.men.female.mdb$ci[3,], 
               mod.switching.men.male.mdb$ci[3,], 
               mod.switching.men.female.dem$ci[3,],
               mod.switching.men.male.dem$ci[3,])

gap <- .1
places <- c(1-gap, 1+gap, 2-gap, 2+gap, 3-gap, 3+gap, 4-gap, 4+gap)
suppressWarnings(plotCI(places, coefs, ui=confs[,2], li=confs[,1], pch=c(16, 15), lwd=2, cex=1, xlim=c(.5, 4.5), ylim=c(-.4, .4), xaxt="n", xlab="", ylab="Effect on Party Switching", main="Male Party Members", cex.main=.9, col=c("red", "blue")))
abline(h=0, lty=3)
legend("topright", lwd=2, pch=c(16,15), col=c("red", "blue"), c("Female Mayor", "Male Mayor"), bty="n")
axis(1, 1:4, labels = c("PT\n", "PSDB\n", "MDB\n", "DEM\n"), tick = F)
dev.off()


party.switching.femalemembers <- rbind(results.formater(mod.switching.women.female.pt,  "PT, Female Mayors"),
                                       results.formater(mod.switching.women.male.pt, "PT, Male Mayors"),
                                       results.formater(mod.switching.women.female.psdb,  "PSDB, Female Mayors"),
                                       results.formater(mod.switching.women.male.psdb, "PSDB, Male Mayors"),
                                       results.formater(mod.switching.women.female.mdb,  "MDB, Female Mayors"),
                                       results.formater(mod.switching.women.male.mdb, "MDB, Male Mayors"),
                                       results.formater(mod.switching.women.female.dem,  "DEM, Female Mayors"),
                                       results.formater(mod.switching.women.male.dem, "DEM, Male Mayors"))
stargazer(as.matrix(party.switching.femalemembers), covariate.labels = c("Model", "Estimate", "95\\% CI", "p", "h", "n"), 
          title="Party-Switching of Female Party Members",
          out="../3_output/appendix/tableS5.tex")


party.switching.femalemembers <- rbind(results.formater(mod.switching.men.female.pt,  "PT, Female Mayors"),
                                       results.formater(mod.switching.men.male.pt, "PT, Male Mayors"),
                                       results.formater(mod.switching.men.female.psdb,  "PSDB, Female Mayors"),
                                       results.formater(mod.switching.men.male.psdb, "PSDB, Male Mayors"),
                                       results.formater(mod.switching.men.female.mdb,  "MDB, Female Mayors"),
                                       results.formater(mod.switching.men.male.mdb, "MDB, Male Mayors"),
                                       results.formater(mod.switching.men.female.dem,  "DEM, Female Mayors"),
                                       results.formater(mod.switching.men.male.dem, "DEM, Male Mayors"))
stargazer(as.matrix(party.switching.femalemembers), covariate.labels = c("Model", "Estimate", "95\\% CI", "p", "h", "n"), 
          title="Party-Switching of Male Party Members",
          out="../3_output/appendix/tableS6.tex")




### TABLE M.1. Percent of first-time congressional candidates who win their election, by career path and gender
federal <- readRDS("../1_data/analysis/data_analysis_CareerPathFederal.rds")

prop.table(table(federal$Held.Local[federal$Woman], federal$Winner[federal$Woman]), margin=1)
prop.table(table(federal$Held.Local[!federal$Woman], federal$Winner[!federal$Woman]), margin=1)
women <- prop.table(table(federal$Held.Local[federal$Woman], federal$Winner[federal$Woman]), margin=1)
men <- prop.table(table(federal$Held.Local[!federal$Woman], federal$Winner[!federal$Woman]), margin=1)
women.mayor <- prop.table(table(federal$Held.Mayor[federal$Woman], federal$Winner[federal$Woman]), margin=1)
men.mayor <- prop.table(table(federal$Held.Mayor[!federal$Woman], federal$Winner[!federal$Woman]), margin=1)
success.rate <- as.data.frame(round(cbind(women[,2], men[,2])*100, 1))
success.rate.mayor <- as.data.frame(round(cbind(women.mayor[,2], men.mayor[,2])*100, 1))
names(success.rate) <- c("Women", "Men")
names(success.rate.mayor) <- c("Women", "Men")
success.rate <- rbind(success.rate, success.rate.mayor[2,])
rownames(success.rate) <- c("No prior local office", "Any local office", "Mayoral office")
success.rate$Odds.Ratio <- success.rate$Men / success.rate$Women

stargazer(success.rate, covariate.labels = c("Background", "Women", "Men", "Odds Ratio"),summary=F, digits=1,
          title="Percent of first-time congressional candidates who win their election, by career path and gender",
          label="tab:path_congress_outcomes",
          out="../3_output/appendix/tableM1.tex")



### TABLE N.1. Campaign donations, by career path and gender of the candidate
federal <- readRDS("../1_data/analysis/data_analysis_CareerPathFederal.rds")

W_m <- mean(federal$All.Donations[federal$Woman & federal$Held.Mayor], na.rm=T)
W_l <- mean(federal$All.Donations[federal$Woman & federal$Held.Local], na.rm=T)
W_n <- mean(federal$All.Donations[federal$Woman & !federal$Held.Local], na.rm=T)
M_m <- mean(federal$All.Donations[!federal$Woman & federal$Held.Mayor], na.rm=T)
M_l <- mean(federal$All.Donations[!federal$Woman & federal$Held.Local], na.rm=T)
M_n <- mean(federal$All.Donations[!federal$Woman & !federal$Held.Local], na.rm=T)

round(matrix(c(W_n, W_l, W_m, M_n, M_l, M_m), byrow=F, nrow=3)/1000, 1)

donations <- data.frame(matrix(c(W_n, W_l, W_m, M_n, M_l, M_m), byrow=F, nrow=3)/1000)
names(donations) <- c("Women", "Men")
rownames(donations) <- c("No prior local office", "Any local office", "Mayoral office")
donations

stargazer(donations, covariate.labels = c("Background", "Women", "Men"),summary=F, digits=1,
          title="Campaign donations, by career path and gender of the candidate",
          label="tab:path_congress_donations",
          out="../3_output/appendix/tableN1.tex")



### TABLE N.2. Campaign funds transfers from party electoral committees and other candidates, by career path and gender of the recipient
federal <- readRDS("../1_data/analysis/data_analysis_CareerPathFederal.rds")

federal$Candidate.Transfers[is.na(federal$Candidate.Transfers) & !is.na(federal$All.Donations)] <- 0
W_m <- mean(federal$Candidate.Transfers[federal$Woman & federal$Held.Mayor], na.rm=T)
W_l <- mean(federal$Candidate.Transfers[federal$Woman & federal$Held.Local], na.rm=T)
W_n <- mean(federal$Candidate.Transfers[federal$Woman & !federal$Held.Local], na.rm=T)
M_m <- mean(federal$Candidate.Transfers[!federal$Woman & federal$Held.Mayor], na.rm=T)
M_l <- mean(federal$Candidate.Transfers[!federal$Woman & federal$Held.Local], na.rm=T)
M_n <- mean(federal$Candidate.Transfers[!federal$Woman & !federal$Held.Local], na.rm=T)

partytransfers <- data.frame(matrix(c(W_n, W_l, W_m, M_n, M_l, M_m), byrow=F, nrow=3)/1000)
names(partytransfers) <- c("Women", "Men")
rownames(partytransfers) <-c("No prior local office", "Any local office", "Mayoral office")
partytransfers

stargazer(partytransfers, covariate.labels = c("Background", "Women", "Men"),summary=F, digits=1,
          title="Campaign funds transfers from party electoral committees and other candidates, by career path and gender of the recipient",
          label="tab:path_congress_partytransfers",
          out="../3_output/appendix/tableN2.tex")


### TABLE O.1. Post-Election Career Path for Federal Deputies
deputies <- readRDS("../1_data/analysis/data_analysis_CareerPathRenominationShifts.rds")

ToMayor <- prop.table(table(deputies$Mayoral.Run, deputies$DESCRICAO_SEXO), margin=2)
StayDeputies <- prop.table(table(deputies$Renominated[!deputies$Mayoral.Run], deputies$DESCRICAO_SEXO[!deputies$Mayoral.Run]), margin=2)

All.Deputies <- round(rbind(ToMayor[2,], StayDeputies[2,])*100, 1)
colnames(All.Deputies) <- c("Women", "Men")
rownames(All.Deputies) <- c("Mid-Term Mayoral Run", "Renomination to Fed Deputies")
All.Deputies.New <- data.frame(t(All.Deputies))
All.Deputies.New$Other <- 100-All.Deputies.New[,2] - All.Deputies.New[,1]
All.Deputies.New$Total <- c(100, 100)
All.Deputies.New <- as.matrix(All.Deputies.New)
colnames(All.Deputies.New) <- c("Mid-Term Mayoral Run", "Renomination to Fed. Deputies", "Other", "Total")

stargazer(partytransfers, covariate.labels = c("Mid-Term Mayoral Run", "Renomination to Federal Deputies", "Other", "Total"), summary=F, digits=1,
          title="Post-Election Career Path for Federal Deputies",
          label="tab:path_postcongress",
          out="../3_output/appendix/tableO1.tex")



### TABLE P.1. Effect of Women Mayors on the Next City Council Elections
women <- readRDS("../1_data/analysis/data_analysis_RDD_women.rds")

mod.candidatepool.nominations <- rdrobust(y=women$Woman.CouncilCandidatesShare.AllParties, x=women$Margin)
mod.candidatepool.winners <- rdrobust(y=women$Woman.Councilors.Share.AllParties, x=women$Margin)
mod.candidatepool.donations <- rdrobust(y=women$Female.Donations.Ratio, x=women$Margin)


candidatepool <- rbind(results.formater(mod.candidatepool.nominations,  "Women as share of council candidates"),
                       results.formater(mod.candidatepool.donations,  "Female / Male campaign donations ratio"),
                       results.formater(mod.candidatepool.winners, "Women as share of elected city councilors"))
stargazer(as.matrix(candidatepool), covariate.labels = c("Dependent Variable", "Estimate", "95\\% CI", "p", "h", "n"),
          title="Effect of Women Mayors on the Next City Council Elections", label="tab:downballot_candidate_pool",
          out="../3_output/appendix/tableP1.tex")







### FIGURE Q.1. Women’s Recruitment and the Gender Gap in Recruitment by Month in the Mayoral Term

data <- readRDS("../1_data/cleaned/data_cleaned_membership_PartyMunicipalityMonth.rds")
panel.data <- readRDS("../1_data/analysis/data_analysis_MunicipalitiesPanel.rds")
terms.with.female.mayors <- paste(panel.data$Year, panel.data$MunCode)[panel.data$Treated.Women]
data$Female.Mayor <- paste(data$PERIODO, data$MunCode) %in% terms.with.female.mayors


pdf("../3_output/appendix/figureQ1.pdf", width=8, height=4)
par(las=1, mfrow=c(1,2), mar=c(4.5,4.5,2,.5))
women <- data[data$Female.Mayor & data$PERIODO <= 2012,] # We are excluding elections after 2012 because the rules about how long a candidate needed to be affiliated with a party (which drive the big affiliation 
                                                         # spike in year 3) changed between the 2012 and 2016 elections, and we want the affiliation cycle to be comparable across terms for the purpose of illustrating 
                                                         # the temporal pattern in the recruitment of new party members
monthly.data.women <- 100000*women[, grepl("F[.]", names(women)) & nchar(names(women)) == 6] / women$Female.Voters
monthly.data.men <- 100000*women[, grepl("M[.]", names(women)) & nchar(names(women)) == 6] / women$Male.Voters
monthly.data <- rbind(colMeans(monthly.data.women), colMeans(monthly.data.men) - colMeans(monthly.data.women))
a <- barplot(monthly.data, ylim=c(0, 140), xaxt="n", ylab="Recruits per Million Voters", xlab="Year in Term", col=c("white", "gray30"), main=c("(A) Recruitment Under Female Mayors"), cex.main = .9)
axis(1, at=a[c(1, 13, 25, 37)], c(1, 2, 3, 4))
legend(1, 140, pch=22, pt.bg=c( "gray30", "white", "gray30"), c( "Gender Gap\n(Male Recruits - Female Recruits)", "Female Recruits"), pt.cex = 1.3, cex=.8, bty="n")

men <- data[!data$Female.Mayor  & data$PERIODO <= 2012,]
monthly.data.women <- 100000*men[, grepl("F[.]", names(men)) & nchar(names(men)) == 6] / men$Female.Voters
monthly.data.men <- 100000*men[, grepl("M[.]", names(men)) & nchar(names(men)) == 6] / men$Male.Voters
monthly.data <- rbind(colMeans(monthly.data.women), colMeans(monthly.data.men) - colMeans(monthly.data.women))
a <- barplot(monthly.data, ylim=c(0, 140), xaxt="n", ylab="Recruits per Million Voters", xlab="Year in Term", col=c("white", "gray30"), main=c("(B) Recruitment Under Male Mayors"), cex.main = .9)
axis(1, at=a[c(1, 13, 25, 37)], c(1, 2, 3, 4))
dev.off()




### FIGURE Q.2. Effect of Incumbency on the Gender Gap, by Year in the Term

women <- readRDS("../1_data/analysis/data_analysis_RDD_women.rds")
men <- readRDS("../1_data/analysis/data_analysis_RDD_men.rds")

y1.women <- rdrobust(y=women$Gender.Gap.Year1, x=women$Margin)
y2.women <- rdrobust(y=women$Gender.Gap.Year2, x=women$Margin)
y3.women <- rdrobust(y=women$Gender.Gap.Year3, x=women$Margin)
y4.women <- rdrobust(y=women$Gender.Gap.Year4, x=women$Margin)
y1.men <- rdrobust(y=men$Gender.Gap.Year1, x=men$Margin)
y2.men <- rdrobust(y=men$Gender.Gap.Year2, x=men$Margin)
y3.men <- rdrobust(y=men$Gender.Gap.Year3, x=men$Margin)
y4.men <- rdrobust(y=men$Gender.Gap.Year4, x=men$Margin)

women.results <- rbind(extract.results(y1.women), extract.results(y2.women), extract.results(y3.women), extract.results(y4.women))
men.results <- rbind(extract.results(y1.men), extract.results(y2.men), extract.results(y3.men), extract.results(y4.men))

pdf("../3_output/appendix/figureQ2.pdf", width=6, height=4.5)
par(las=1)
gap <- .1
plotCI(1:4-gap, men.results[,1], li=men.results[,2], ui=men.results[,3], pch=16, xaxt="n", xlab="Year in Term", ylab="Effect on Gender Gap", xlim=c(.8, 4.2), ylim=c(-2, 1), col="gray60", cex=1.5, lwd=2)
lines(1:4-gap, men.results[,1], col="gray60", lwd=1)
points(1:4-gap, men.results[,1], cex=1.2, col="white", pch=16)
plotCI(1:4+gap, women.results[,1], li=women.results[,2], ui=women.results[,3], pch=16, xaxt="n", xlab="Year in Term", ylab="Effect on Gender Gap", xlim=c(.8, 4.2), add=T, lwd=2, cex=1.5)
lines(1:4+gap, women.results[,1], lwd=2)
legend("topright", col=c("gray60", "black"), pch=c(21, 16), bg=c("white", "black"), c("Male Mayors", "Female Mayors"))
abline(h=0, lty=3)
axis(1, 1:4)
dev.off()


byyear <- rbind(results.formater(y1.women,  "Year 1, Female Mayors"),
                results.formater(y1.men,  "Year 1, Male Mayors"),
                results.formater(y2.women,  "Year 2, Female Mayors"),
                results.formater(y2.men,  "Year 2, Male Mayors"),
                results.formater(y3.women,  "Year 3, Female Mayors"),
                results.formater(y3.men,  "Year 3, Male Mayors"),
                results.formater(y4.women,  "Year 4, Female Mayors"),
                results.formater(y4.men,  "Year 4, Male Mayors"))
stargazer(as.matrix(byyear), covariate.labels = c("Model", "Estimate", "95\\% CI", "p", "h", "n"), 
          title="Effect of Incumbency by Year",
          out="../3_output/appendix/tableS7.tex")




cat("Appendix analyses complete.\n")






